package cn.hyxy.hadoop;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;


public class Demo08_CombinerMR extends Configured implements Tool{

	@Override
    public int run(String[] args) throws Exception {
        if (args.length != 2) {
            System.out.println("usage ...");
            return -1;
        }
        // 7:声明Job
        Configuration config = getConf();
        FileSystem fs = FileSystem.get(config);
        Path path = new Path(args[1]);
        if (fs.exists(path)) {
            fs.delete(path, true);
        }
        // 8:Job
        Job job = Job.getInstance(config, "Combiner");
        job.setJarByClass(getClass());
        
        job.setMapperClass(MyMapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(LongWritable.class);

        
        job.setCombinerClass(MyCombiner.class);
        
        //
//        job.setNumReduceTasks(0); //不执行Reducer 
        
        FileInputFormat.addInputPath(job, new Path(args[0]));
        FileOutputFormat.setOutputPath(job, path);
        return job.waitForCompletion(true) ? 0 : 1;
    }

    public static void main(String[] args) throws Exception {
        int code = ToolRunner.run(new Demo08_CombinerMR(), args);
        System.exit(code);
    }
    
  

    //1:开发Mapper类
    public static class MyMapper extends Mapper<LongWritable, Text, Text, LongWritable> {
    	private LongWritable value2=new LongWritable(1);
        @Override
        public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
         
            String[] strs = value.toString().split("\\s+");            
            for (String string : strs) {
				if (string.trim().equals("")) {
					continue;
				}
				context.write(new Text(string), value2);
			}
        }
    }
    
    public static class MyCombiner extends Reducer<Text, LongWritable, Text, LongWritable>{
    	@Override
    	protected void reduce(Text key3, Iterable<LongWritable> value3,
    			Reducer<Text, LongWritable, Text, LongWritable>.Context context) throws IOException, InterruptedException {
    		long sum=0;
    		for (LongWritable longWritable : value3) {
				sum+=longWritable.get();
			}
    		context.write(key3, new LongWritable(sum));
    	}
    }
}
